package com.shundr.auth.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.ContextMenu;
import android.view.TextureView;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.SpinnerAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.shundr.auth.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.base.SimpleBaseActivity;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.DateUtils;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.common.view.CListView;
import com.shundr.auth.common.view.CListView.OnLoadMoreListener;
import com.shundr.auth.common.view.CListView.OnRefreshListener;
import com.shundr.auth.common.view.DialogChoiceBeginEndTime;
import com.shundr.auth.common.view.MyDatePickerDialog;
import com.shundr.auth.frame.constant.LContext;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.http.LHttpRequest;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.LLoader;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.adapter.AuthOwnnerItemAdapter;
import com.shundr.auth.user.adapter.AuthUserItemAdapter;
import com.shundr.auth.user.dao.TruckDao;
import com.shundr.auth.user.http.UserRequest;
import com.shundr.auth.user.model.AuthOwnnerInfo;
import com.shundr.auth.user.model.UserInfo;
import com.shundr.truck.adapter.SocialTruckAdapter;
import com.shundr.truck.http.UserTruckRequest;
import com.shundr.truck.model.TruckInfo;

/**
 * AuthUserByDateActivity
 * 
 * @author Administrator
 *
 */
public class SocialTruckListActivity extends SimpleBaseActivity implements
		View.OnClickListener {
	private int status = -1;
	private int pageNo = 1;
	private static final int PAGE_SIZE = LContext.PAGE_SIZE;

	private Date begin;
	private Date end;

	private CListView mListView;
	private SocialTruckAdapter mAdapter;
	private EditText etBegin;
	private EditText etEnd;

	private TextView tvCount;

	private List<TruckInfo> mList = new ArrayList<TruckInfo>();
	private RelativeLayout mLayoutNoContent;
	private TruckDao truckDao;
	private UserTruckRequest request;

	private int index = -1;
	private List<TruckInfo> infos = new ArrayList<TruckInfo>();// upload info
																// list
	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();
	private TruckInfo upItem;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			LLogger.e("msg.what:" + msg.what);
			switch (msg.what) {
			case UserTruckRequest.ADD_USER_TRUCK_RETURN_SUCCESSED:

				if (index < 0) {
					upItem.setUpStatus(1);
					// upload done
					updateDB();
				} else if (index >= (infos.size() - 1)) {
					infos.get(index).setUpStatus(1);
					updateDB();
				} else {
					infos.get(index).setUpStatus(1);
					index++;
					uploadTruck(infos.get(index));
					ProgressDialogHelper.setMessageText(String.format(
							"上传进度：%1$s", index));
				}

				break;
			case LHttpRequest.REQUEST_FAILED:
				ToastHelper.toastLong(mContext, msg.obj.toString());
				if (index < 0) {
					upItem.setUpStatus(2);
					upItem.setUpFailMsg(msg.obj.toString());
					// upload done
					updateDB();
				} else if (index >= (infos.size() - 1)) {
					// upload done
					infos.get(index).setUpStatus(2);
					infos.get(index).setUpFailMsg(msg.obj.toString());
					updateDB();
				} else {
					infos.get(index).setUpStatus(2);
					infos.get(index).setUpFailMsg(msg.obj.toString());
					index++;
					uploadTruck(infos.get(index));
					ProgressDialogHelper.setMessageText(String.format(
							"上传进度：%1$s", index));
				}

				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		request = new UserTruckRequest(mContext, mHandler);
		truckDao = new TruckDao();

		begin = end = new Date();

		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		// 生成一个SpinnerAdapter
		SpinnerAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.array_up_status, R.layout.item_actionbar_spinner);
		// 为ActionBar设置下拉菜单和监听器
		mActionBar.setListNavigationCallbacks(adapter, new DropDownListenser());
		setContentView(R.layout.activity_user_list);

		etBegin = (EditText) findViewById(R.id.et_begin);
		etEnd = (EditText) findViewById(R.id.et_end);
		etBegin.setOnClickListener(this);
		etEnd.setOnClickListener(this);
		tvCount = (TextView) findViewById(R.id.tv_count);
		mListView = (CListView) findViewById(R.id.lv_list);
		mLayoutNoContent = (RelativeLayout) findViewById(R.id.layout_no_content);

		mAdapter = new SocialTruckAdapter(mContext, mList);
		mListView.setAdapter(mAdapter);

		mListView.setCanLoadMore(false);
		mListView.setAutoLoadMore(false);
		mListView.setCanRefresh(false);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				TruckInfo info = mList.get(position - 1);
				if (info.getUpStatus() != 1) {
					showOperationDialog(info, info.getUpStatus() == 2);
				}

			}

		});

	}

	private void uploadAll() {
		ProgressDialogHelper.show(mContext, "正在上传数据！");
		infos = truckDao.getAllTruckInfosByStatus(0);
		if (infos.size() <= 0) {
			ToastHelper.toastShort(mContext, "没有需要上传的信息！");
			ProgressDialogHelper.dismiss();
		} else {
			index = 0;
			uploadTruck(infos.get(0));
		}
	}

	private void uploadTruck(TruckInfo info) {
		// upload
		if (index < 0) {
			upItem = info;
		}
		String expectedAddr = "";
		String expectedAddrCode = "";

		if (!StringUtil.isNull(info.truckForwardCity1)) {
			expectedAddr = info.truckForwardCity1;
			expectedAddrCode = String.valueOf(info.truckForwardCity1Code);
		}

		if (!StringUtil.isNull(info.truckForwardCity2)) {
			expectedAddr = expectedAddr + "-" + info.truckForwardCity2;
			expectedAddrCode = expectedAddrCode + "-"
					+ String.valueOf(info.truckForwardCity2Code);
		}

		if (!StringUtil.isNull(info.truckForwardCity3)) {
			expectedAddr = expectedAddr + "-" + info.truckForwardCity3;
			expectedAddrCode = expectedAddrCode + "-"
					+ String.valueOf(info.truckForwardCity3Code);
		}

		if (!StringUtil.isNull(info.truckForwardCity4)) {
			expectedAddr = expectedAddr + "-" + info.truckForwardCity4;
			expectedAddrCode = expectedAddrCode + "-"
					+ String.valueOf(info.truckForwardCity4Code);
		}

		PictureInfo picInfo = new PictureInfo();
		Bitmap myBitmap = BitmapFactory.decodeFile(info.getTruckPic());
		picInfo.setFileBase64Body(Base64Util.encodeImage(myBitmap));
		myBitmap.recycle();
		picInfo.setFilename(info.getTruckPic());
		picInfo.setType(PictureInfo.FileType.truck);

		mPictures.clear();
		mPictures.add(picInfo);

		String base64 = JsonUtil.toJson(mPictures);

		request.addUserAndTruck(info.truckerPhone, info.truckPlateNumber,
				info.truckCapacity, info.truckLength, info.truckTypeCode,
				expectedAddr, expectedAddrCode, base64);
	}

	private void updateDB() {
		ProgressDialogHelper.setMessageText("正在更新本地数据...");
		if (index < 0) {
			updateDB(upItem);
		} else {
			truckDao.updateMore(infos);
		}
		ProgressDialogHelper.dismiss();
		onRefresh();
	}

	private void updateDB(TruckInfo info) {
		truckDao.update(info);
	}

	public void onRefresh() {

		etBegin.setText(DateUtils.formateDateString(begin));
		etEnd.setText(DateUtils.formateDateString(end));
		// pageNo = 1;
		if (status == -1) {
			mList = truckDao.getAllTruckInfosByDate(begin, end);
		} else {
			mList = truckDao.getTruckListByStatusAndDate(status, begin, end);
		}
		mAdapter.setData(mList);
		tvCount.setText(String.format("一共有%s辆车", mList.size()));
		if (mList.size() > 0) {
			mListView.setVisibility(View.VISIBLE);
			mLayoutNoContent.setVisibility(View.GONE);
		} else {
			mListView.setVisibility(View.GONE);
			mLayoutNoContent.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View view) {

		switch (view.getId()) {
		case R.id.et_begin:
			showDatePicker(true);
			break;

		case R.id.et_end:
			showDatePicker(false);
			break;

		default:
			break;
		}

	}

	private void showOperationDialog(final TruckInfo info, boolean isFailed) {
		Builder builder = new AlertDialog.Builder(mContext)
				.setTitle(isFailed ? "失败详情" : "选择操作")
				.setCancelable(true)
				.setMessage(isFailed ? info.getUpFailMsg() : "请选择需要进行的操作！")
				.setPositiveButton(isFailed ? "重新上传" : "上传数据",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int id) {
								index = -1;
								uploadTruck(info);
								dialog.dismiss();
							}
						})
				.setNegativeButton("删除记录",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int id) {
								truckDao.delete(info);
								dialog.dismiss();
								onRefresh();
								ToastHelper.toastShort(mContext, "记录删除成功！");
							}
						});
		builder.show();
	}

	private void showDatePicker(final boolean isBegin) {
		final Calendar calendar = Calendar.getInstance();
		calendar.setTime(isBegin ? begin : end);
		MyDatePickerDialog dialog = new MyDatePickerDialog(mContext,
				new MyDatePickerDialog.OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int y, int m, int d) {
						calendar.set(y, m, d);
						if (isBegin) {
							if (DateUtils.isAfter(calendar.getTime(), end)) {
								ToastHelper.toastShort(mContext,
										"选择的开始时间晚于结束时间，请重新选择！");
								return;
							}
							begin = calendar.getTime();
						} else {
							if (DateUtils.isAfter(begin, calendar.getTime())) {
								ToastHelper.toastShort(mContext,
										"选择的结束时间早于开始时间，请重新选择！");
								return;
							}
							end = calendar.getTime();
						}
						onRefresh();
					}
				}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));

		dialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_upload, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.menu_upload:
			uploadAll();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (resultCode) {
		case 500:
			onRefresh();
			break;

		default:
			break;
		}
	}

	class DropDownListenser implements OnNavigationListener {

		@Override
		public boolean onNavigationItemSelected(int itemPosition, long itemId) {
			switch (itemPosition) {
			case 0:
				status = 0;
				break;
			case 1:
				status = -1;
				break;
			case 2:
				status = 1;
				break;
			case 3:
				status = 2;
				break;
			case 4:
				status = 3;
				break;
			default:
				break;
			}
			onRefresh();
			return true;
		}

	}
}
